// pages/mall/mall.ts
import animationHelper from '../..//utils/animation';
import api from "../../utils/api"
import utils from "../../utils/utils"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    toTop: 0 as number,
    // 静态页面
    sortItems: [
      {
        text: '综合排序',
        showSort: false,
        value:'RECOMMEND'
      },
      {
        text: '销量',
        showSort: false,
        value:"SALES"
      },
      {
        text: '价格',
        direction: 'ASC',  // 排序方向，可以是 'ASC' 或 'DESC'
        showSort: false,
        value:"PRICE_"
      }
    ] as Sort[],
    showFilter: false as boolean,
    animation: null as WechatMiniprogram.Animation | null,
    animationData: {} as any,
    page: 1,
    pageSize: 10,
    commodityList: [] as CommodityModel[],//商品列表
    totalCount: 0 as number,
    categoryList: [] as CategoryModel[],
    categoryIds: [] as Array<number>,//分类商品ID
    sort:'' as string
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const app = getApp<IAppOption>();
    this.setData({
      toTop: app.globalData.statusBarHeight + app.globalData.navHeight
    })
    this.getCommodityList("add");
    this.getCategories();
  },
  // 点击
  switchSort(e: any): void {
    const index = e.currentTarget.dataset.index;
    // 第一次点，展示sort图标
    if (!this.data.sortItems[index].showSort) {
      this.data.sortItems.map(item => {
        item.showSort = false
      })
      this.data.sortItems[index].showSort = true
      this.setData({
        sortItems: this.data.sortItems
      })
    }
    // 只有价格有升降序 
    else if(index == 2){
      // 非第一次，切换排序顺序
      this.data.sortItems[index].direction = this.data.sortItems[index].direction == 'ASC' ? 'DESC' : 'ASC';
      this.setData({
        sortItems: this.data.sortItems
      });
    }
    const sort = index == 2 ? this.data.sortItems[index].value + this.data.sortItems[index].direction : this.data.sortItems[index].value
    this.setData({
      sort,
      page:1,
      totalCount:0
    })
    this.getCommodityList();
  },
  // 展示过滤弹窗
  showFilter(): void {
    const animation = animationHelper.createAnimation(500, 'ease');
    this.setData({
      animation: animation
    });
    animationHelper.showAnimation(animation, 500, this.setData.bind(this), 'showFilter');
  },
  closeFilter(): void {
    const animation = this.data.animation;
    animationHelper.closeAnimation(animation, 500, this.setData.bind(this), 'showFilter');
  },
  // 去商品详情
  toDetail(e:any): void {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/malldetail/malldetail?type=normal&id=" + id
    })
  },
  toSearch(): void {
    wx.navigateTo({
      url: "/pages/search/search"
    })
  },
  // 获取商品列表
  async getCommodityList(type: string = 'reset'): Promise<void> {
    const { page, pageSize, commodityList, categoryIds,sort } = this.data
    const params = {
      page,
      pageSize,
      categoryIds,
      sort
    }
    const res = await api.commodity.getCommodityList(params);
    if (res.data.code == '000') {
      if (res.data.data && res.data.data.list) {
        res.data.data.list.forEach(item => {
          item.price = utils.priceToYuan(item.price as number)
          item.originalPrice = utils.priceToYuan(item.originalPrice as number)
        })
        this.setData({
          commodityList: type == "add" ? [...commodityList, ...res.data.data.list] : res.data.data.list,
          totalCount: res.data.data.totalCount,
          page: type == "add"? page + 1:1
        })
      }
    } else {
      wx.showToast({
        title: res.data.message as string,
        icon: "error"
      })
    }
  },
  // 获取子组件传过来的分类ID
  getCId(e: any): void {
    this.closeFilter();
    this.setData({
      categoryIds: e.detail.ids,
      categoryList: e.detail.list,
      page:1
    })
    this.getCommodityList();
  },
  // 获取分类
  async getCategories(): Promise<void> {
    const res = await api.commodity.getCategories();
    if (res.data.code == "000") {
      if (res.data.data) {
        // 添加choose属性
        res.data.data.forEach(item => {
          if (item.children) {
            item.children.forEach(i => {
              i.choose = false
            })
          }
        })
        this.setData({
          categoryList: res.data.data,
        })
      }
    } else {
      wx.showToast({
        title: res.data.message as string,
        icon: "error"
      })
    }
  },
  toCart(): void {
    wx.navigateTo({
      url:"/pages/cart/cart"
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log("触底了")
    if (this.data.totalCount == this.data.commodityList.length) {
      return
    }
    this.getCommodityList("add");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})